package ceph

import (
	"crypto/hmac"
	"crypto/sha1"
	"encoding/json"
	"net/http"
	"net/url"
	"fmt"
	"io"
	"time"
	"errors"
	"encoding/base64"
)

func makeHMac(key []byte, data []byte) []byte {
	hash := hmac.New(sha1.New, key)
	hash.Write(data)
	return hash.Sum(nil)
}

type Response struct {
	Keys []Credentials `json:"keys"`
}

type Credentials struct {
	AccessKey string `json:"access_key"`
	SecretKey string `json:"secret_key"`
	User      string `json:"user"`
}


func CreateCephUser(uid, display, email, accessKey, secretKey string) (s3key, secret string, err error){
	// session = GetCephAdminConn()
	client := &http.Client{}

	//url
	baseURL := "http://192.168.1.224:80/admin/user?format=json"

	// 创建 URL 对象
	u, err := url.Parse(baseURL)
	if err != nil {
		//.GetLogger().Errorf("Error parsing base URL: %v", err)
		return "", "", err
	}

	// 创建 URL 查询参数
	queryParams := url.Values{}
	queryParams.Add("uid", uid)
	queryParams.Add("display-name", display)
	queryParams.Add("email", email)
	queryParams.Add("user-caps", "usage=read;users=read;buckets=read,write;metadata=read")
	if accessKey != "" && secretKey != "" {
		queryParams.Add("access-key", accessKey)
		queryParams.Add("secret-key", secretKey)
	}

	// 将查询参数添加到 URL
	u.RawQuery = queryParams.Encode()

	// 创建请求
	req, err := http.NewRequest("PUT", u.String(), nil)
	if err != nil {
		//.GetLogger().Errorf("Error creating request: %v", err)
		return "", "", err
	}

	// 生成签名
	utcTime := time.Now().UTC()
	timestamp := utcTime.Format("Mon, 2 Jan 2006 15:04:05") + " +0000"
	strToSign := "PUT\n\n\n" + timestamp + "\n/admin/user"
	signature := makeHMac([]byte(cephConn.Secret), []byte(strToSign))

	req.Header.Add("Date", timestamp)
	req.Header.Add("Authorization", "AWS "+cephConn.S3key+":"+base64.StdEncoding.EncodeToString(signature))

	resp, err := client.Do(req)
	if err != nil {
		//your_logger_package.GetLogger().Errorf("Error sending request: %v", err)
		return "", "", err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		//bodyBytes, _ := io.ReadAll(resp.Body)
		//your_logger_package.GetLogger().Warnf("Request not ok with status: %d, body: %s", resp.StatusCode, string(bodyBytes))
		return "", "", fmt.Errorf("request failed with status: %d", resp.StatusCode)
	}

	// 读取响应体内容
	bodyBytes, err := io.ReadAll(resp.Body)
	if err != nil {
		//your_logger_package.GetLogger().Errorf("Error reading response body: %v", err)
		return "", "", err
	}

	// 解析响应内容
	var response Response
	if err := json.Unmarshal(bodyBytes, &response); err != nil {
		//your_logger_package.GetLogger().Errorf("Error parsing response: %v", err)
		return "", "", err
	}

	if len(response.Keys) > 0 {
		s3key = response.Keys[0].AccessKey
		secret = response.Keys[0].SecretKey
	} else {
		return "", "", errors.New("no keys found in the response")
	}

	return s3key, secret, nil
}